<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>WebSocket</title>
  <style>
    #sendBlock {
      display: none;
    }
  </style>
</head>

<body>
  <div id="userBlock">
    姓名：<input id="username" type="text" />
    <button id="connectBtn">连接</button>
  </div>
  <div id="sendBlock">
    <input id="sendText" type="text" />
    <button id="sendBtn">发送消息</button>
    <br />
    <textarea rows="16" cols="50" id="chatRecord" disabled></textarea>
  </div>
  <script type="module">
    function canNotificate() {
      if (!("Notification" in window)) {
        alert("此浏览器不支持通知。");
        return;
      }
      Notification.requestPermission().then((result) => {
        console.log(result);
      });
    }
    canNotificate();

    const username = document.querySelector("#username");
    const connectBtn = document.querySelector("#connectBtn");
    const sendBlock = document.querySelector("#sendBlock");
    const sendText = document.querySelector("#sendText");
    const sendBtn = document.querySelector("#sendBtn");
    const chatRecord = document.querySelector("#chatRecord");

    function addToRecord(str = "") {
      if (str) {
        chatRecord.value += `${str}\n`;
      }
    }

    let ws = null;
    connectBtn.addEventListener("click", () => {
      if (!username.value) {
        alert("请输入姓名");
        return;
      }
      ws = new WebSocket("http://sote-pi.local:8000/");

      ws.addEventListener("open", function (evt) {
        const msg = JSON.stringify({
          type: "SYSTEM",
          username: username.value,
          content: "",
        });
        ws.send(msg);
        addToRecord(`客户端open了`);
      });
      ws.addEventListener("message", function (evt) {
        const msg = JSON.parse(evt.data);
        if (msg.type === "TEXT") {
          addToRecord(`${msg.username}说：${msg.content}`);
          new Notification(`${msg.username}说`, { body: msg.content });
        }
        else if (msg.type === "SYSTEM") {
          addToRecord(`${msg.content}`);
        }
      });
      ws.addEventListener("close", function (evt) {
      });
      ws.addEventListener("error", function (evt) {
      });

      sendBlock.style.display = "block";
      userBlock.style.display = "none";
    });

    sendBtn.addEventListener("click", () => {
      if (ws === null) {
        return;
      }
      const msg = JSON.stringify({
        type: "TEXT",
        username: username.value,
        content: sendText.value
      });
      ws.send(msg);
    });


  </script>
</body>

</html>
